<template>
  <a-drawer
    title="修改服务"
    :maskClosable="false"
    width=650
    placement="right"
    :closable="false"
    @close="onClose"
    :visible="serviceEditVisiable"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">
    <a-form :form="form">
      <a-form-item label='封面' v-bind="formItemLayout">
        <div class="clearfix">
          <a-upload
            listType="picture-card"
            :beforeUpload="beforeUpload"
            :remove="handleRemove"
            :fileList="fileList"
            @preview="handlePreview"
          >
            <div v-if="fileList.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">Upload</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </div>
      </a-form-item>
      <a-form-item label='服务分类：' v-bind="formItemLayout">
        <a-select
          mode="single"
          :allowClear="true"
          style="width: 100%"
          @change="handleCategoryChange"
          v-decorator="['categoryId',
           {rules: [
                    { required: true, message: '不能为空'}
          ]}]">
          <a-select-option v-for="type in categoryList" :key="type.key" :title="type.value">{{type.value}}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='服务名称' v-bind="formItemLayout">
        <a-input v-decorator="['name',
                   {rules: [
                    { required: true, message: '不能为空'},
                    { max: 30, message: '长度不能超过30个字符'}
                  ]}]"/>
      </a-form-item>
      <a-form-item label='标识符SN' v-bind="formItemLayout" v-model="serviceInfo.sn">
        <span>{{serviceInfo.sn}}</span>
      </a-form-item>
      <a-form-item label='顶部颜色值' v-bind="formItemLayout">
        <a-input placeholder="0ee0e2"
                 v-decorator="['color',
                   {rules: [
                    { required: true, message: '不能为空'},
                    { max: 30, message: '长度不能超过30个字符'}
                  ]}]"/>
      </a-form-item>
      <a-form-item label='服务描述' v-bind="formItemLayout">
        <a-input v-model="serviceInfo.desc"
                 v-decorator="['desc',
                   {rules: [
                    { required: true, message: '不能为空'},
                    { max: 30, message: '长度不能超过30个字符'}
                  ]}]"/>
      </a-form-item>
      <a-form-item label='是否免费' v-bind="formItemLayout">
        <a-switch defaultChecked :checked="enable.isFree" @change="isFreeChange"/>
      </a-form-item>
      <a-form-item label='状态' v-bind="formItemLayout">
        <a-switch defaultChecked :checked="enable.status" @change="statusChange"/>
      </a-form-item>
    </a-form>
    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
  </a-drawer>
</template>
<script>
const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 18 }
}
export default {
  name: 'ServiceEdit',
  props: {
    serviceEditVisiable: {
      default: false
    },
    categoryList: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      loading: false,
      formItemLayout,
      form: this.$form.createForm(this),
      serviceInfo: {
        cover: '',
        categoryId: '',
        categoryName: ''
      },
      fileList: [],
      previewVisible: false,
      previewImage: '',
      enable: { status: true, isFree: true }
    }
  },
  mounted () {
    this.initCategory()
  },
  watch: {
    serviceEditVisiable () {
      if (this.serviceEditVisiable) {
        this.form.getFieldDecorator('categoryId')
      }
    }
  },
  methods: {
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      if (!isJPG && !isPNG) {
        this.$message.error('You can only upload JPG or PNG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      // 创建FormData对象
      let param = new FormData()
      // 将得到的文件流添加到FormData对象
      param.append('file', file, file.name)
      this.$upload('oss/upload', param).then(result => {
        if (result.data.code === '1') {
          this.fileList = []
          this.serviceInfo.cover = result.data.datas.url
          file.uid = Math.random()
          file.status = 'done'
          file.url = result.data.datas.url
          this.fileList.push(file)
        } else {
          this.loading = false
          this.serviceInfo.cover = ''
          this.fileList = []
          this.$message.error('图片上传失败')
        }
      }).catch((data) => {
        this.loading = false
        this.$message.error('新增失败')
      })
      return false
    },
    handlePreview (file) {
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    handleRemove (file) {
      this.fileList = []
      this.serviceInfo.cover = ''
    },
    handleCancel () {
      this.previewVisible = false
    },
    initCategory () {
      this.$get('category/findAll').then((r) => {
        let result = r.data
        result.forEach((res) => {
          this.categoryList.push({
            key: res.id,
            value: res.name
          })
        })
      })
    },
    handleCategoryChange (key, option) {
      this.serviceInfo.categoryId = key || ''
      this.serviceInfo.categoryName = option.componentOptions.propsData.title || ''
    },
    handleSNCheck (rule, value, callback) {
      let sn = value.trim()
      if (sn.length) {
        this.$get(`serviceInfo/check/${sn}`).then((r) => {
          if (r.data) {
            callback()
          } else {
            this.validateStatus = 'error'
            callback(new Error('抱歉，该SN已存在'))
          }
        })
      } else {
        callback()
      }
    },
    statusChange (checked) {
      this.enable.status = checked
    },
    isFreeChange (checked) {
      this.enable.isFree = checked
    },
    reset () {
      this.loading = false
      this.serviceInfo = {
        cover: '',
        categoryId: '',
        categoryName: ''
      }
      this.fileList = []
      this.form.resetFields()
      this.enable = {status: true, isFree: true}
    },
    onClose () {
      this.reset()
      this.$emit('close')
    },
    setValue () {
      if (this.enable.status === true) {
        this.serviceInfo.status = 'ENABLE'
      } else {
        this.serviceInfo.status = 'DISABLE'
      }
      if (this.enable.isFree === true) {
        this.serviceInfo.isFree = 'true'
      } else {
        this.serviceInfo.isFree = 'false'
      }
    },
    setFormValues ({...record}) {
      let fields = ['name', 'sn', 'color', 'desc', 'categoryId']
      Object.keys(record).forEach((key) => {
        if (fields.indexOf(key) !== -1) {
          this.form.getFieldDecorator(key)
          let obj = {}
          obj[key] = record[key]
          this.form.setFieldsValue(obj)
        }
      })
      this.serviceInfo = record
      this.serviceInfo.categoryId = record.categoryId
      this.serviceInfo.categoryName = record.categoryName
      this.fileList = [{uid: Math.random(), status: 'done', url: record.cover, name: record.name}]
      this.init()
    },
    init () {
      if (this.serviceInfo.status === 'ENABLE') {
        this.enable.status = true
      } else {
        this.enable.status = false
      }
      if (this.serviceInfo.isFree === 'true') {
        this.enable.isFree = true
      } else {
        this.enable.isFree = false
      }
    },
    handleSubmit () {
      this.setValue()
      this.form.validateFields((err, values) => {
        if (!err) {
          let serviceInfo = this.form.getFieldsValue()
          serviceInfo.id = this.serviceInfo.id
          serviceInfo.sn = this.serviceInfo.sn
          serviceInfo.status = this.serviceInfo.status
          serviceInfo.isFree = this.serviceInfo.isFree
          serviceInfo.cover = this.serviceInfo.cover
          serviceInfo.categoryId = this.serviceInfo.categoryId
          serviceInfo.categoryName = this.serviceInfo.categoryName
          this.$put('serviceInfo', {
            ...serviceInfo
          }).then(result => {
            if (result.data.code === '1') {
              this.reset()
              this.$emit('success')
            } else {
              this.$message.error('修改失败')
            }
          }).catch((data) => {
            this.loading = false
            this.$message.error('修改失败')
          })
        }
      })
    }
  }
}
</script>
